Page({
  data: {
    messages: [],
    inputValue: '',
    scrollTop: 0,
    historyMessages: []  // 添加历史消息数组
  },

  onLoad() {
    // 页面加载时初始化
    this.setData({
      messages: [],
      historyMessages: []
    });
  },

  onInput(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },

  sendMessage() {
    if (!this.data.inputValue.trim()) return;
    
    const userMessage = {
      type: 'user',
      content: this.data.inputValue,
      time: new Date().toLocaleTimeString()
    };

    // 更新历史消息
    const newHistoryMessages = [...this.data.historyMessages];
    newHistoryMessages.push({
      role: 'user',
      content: [{
        type: 'text',
        text: this.data.inputValue
      }]
    });

    this.setData({
      messages: [...this.data.messages, userMessage],
      historyMessages: newHistoryMessages,
      inputValue: ''
    }, () => {
      this.scrollToBottom();
      this.getAIResponse();
    });
  },

  scrollToBottom() {
    wx.createSelectorQuery()
      .select('.message-list')
      .boundingClientRect((rect) => {
        if (rect) {
          this.setData({
            scrollTop: rect.height
          });
        }
      })
      .exec();
  },

  getAIResponse() {
    const userInfo = wx.getStorageSync('userInfo');
    const userId = userInfo.id || userInfo.userId || "default_user";
    
    // 获取最后一条用户消息
    const lastMessage = this.data.messages[this.data.messages.length - 1];
    
    // 构建请求数据，确保格式完全符合API要求
    const requestData = {
      assistant_id: "zchxw3PRIqJb",
      user_id: "user_" + userId, // 确保user_id是字符串类型
      stream: false,
      messages: [{
        role: "user",
        content: [{
          type: "text",
          text: String(lastMessage.content) // 确保文本内容是字符串类型
        }]
      }]
    };
    
    console.log('发送请求数据：', JSON.stringify(requestData, null, 2));

    wx.request({
      url: 'https://yuanqi.tencent.com/openapi/v1/agent/chat/completions',
      method: 'POST',
      header: {
        'X-Source': 'openapi',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer sxz6V5gXGEUwb5ZiAUx6iUUoGVl9JND1'
      },
      data: requestData,
      success: (res) => {
        wx.hideLoading();
        console.log('API响应：', res.data);
        
        if (res.statusCode !== 200) {
          this.handleError(`请求失败: ${res.data?.error?.message || '未知错误'}`);
          return;
        }

        if (res.data.choices && res.data.choices[0]) {
          const choice = res.data.choices[0];
          
          if (choice.finish_reason === 'sensitive') {
            this.handleError('抱歉，您的问题涉及敏感内容，请换个话题。');
            return;
          }

          if (choice.message && choice.message.content) {
            const aiMessage = {
              type: 'ai',
              content: choice.message.content,
              time: new Date().toLocaleTimeString()
            };

            this.setData({
              messages: [...this.data.messages, aiMessage]
            }, () => {
              this.scrollToBottom();
            });
          }
        }
      },
      fail: (err) => {
        console.error('请求失败：', err);
        this.handleError('网络连接失败，请检查网络后重试');
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  handleError(message) {
    const errorMessage = {
      type: 'ai',
      content: message,
      time: new Date().toLocaleTimeString()
    };
    
    this.setData({
      messages: [...this.data.messages, errorMessage]
    }, () => {
      this.scrollToBottom();
    });
  }
});